//
//  YBCenterVC.m
//  WuyouTang
//
//  Created by YB007 on 2022/5/30.
//  Copyright © 2022 cat. All rights reserved.
//

#import "YBCenterVC.h"

#import "YBCenterTopView.h"
#import <TYTabPagerBar.h>
#import <TYPagerController.h>
#import "MessageListModel.h"
#import "CenterListVC.h"
#import "WYTShopListVC.h"

@interface YBCenterVC ()<UIScrollViewDelegate,TYTabPagerBarDelegate,TYTabPagerBarDataSource,TYPagerControllerDelegate,TYPagerControllerDataSource,ListScrollDelegate>
{
    CGFloat scrContentH;
    CGFloat segStartY;
    
    int _is_shop;
    int _like_switch;
    int _collect_switch;
    
}
@property(nonatomic,strong)YBCenterTopView *topView;

@property(nonatomic,strong)TYTabPagerBar *tabBar;
@property(nonatomic,strong)TYPagerController *pagerController;
@property(nonatomic,strong)NSArray *dataArray;

@property(nonatomic,assign)BOOL followed;
@property(nonatomic,strong)UIScrollView *scrollview;

@property(nonatomic,strong)CenterListVC *listVC1;
@property(nonatomic,strong)CenterListVC *listVC2;
@property(nonatomic,strong)CenterListVC *listVC3;
@property(nonatomic,strong)WYTShopListVC *shopListVC;

@end

@implementation YBCenterVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self pullData];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_topView removeLivingAnimation];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    _otherUid ? _otherUid:(_otherUid=[Config getOwnID]);
    
    scrContentH = 0;
    _followed = NO;
    
    [self.view addSubview:self.scrollview];
    self.view.backgroundColor = UIColor.whiteColor;
    if (@available(iOS 11.0, *)){
        _scrollview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.rightBtn setImage:[UIImage imageNamed:@"center_more"] forState:0];
    if (![_otherUid isEqual:[Config getOwnID]]) {
        //他人
        self.leftBtn.hidden = NO;
        self.rightBtn.hidden = NO;
    }else{
        //自己
        self.leftBtn.hidden = YES;
        self.rightBtn.hidden = YES;
    }
    //从其他页面push过来
    if (_isPush) {
        self.leftBtn.hidden = NO;
        }
    // 0 - 系统管理员
    if ([_otherUid isEqual:@"0"]) {
        self.rightBtn.hidden = YES;
    }
    //动态改变
    self.subNavi.alpha = 0;
    self.rightBtn.hidden = YES;
    
    [_tabBar reloadData];
    [_pagerController reloadData];
    
}

-(void)pullData {
//    if([_otherUid isEqual:@"-9999"]){
//        _otherUid = [Config getOwnID];
//    }
    NSString *url = [NSString stringWithFormat:@"User.getUserHome&uid=%@&touid=%@",[Config getOwnID],_otherUid];
    [WYNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            NSDictionary *infoDic = [info firstObject];
            if ([_otherUid isEqual:[Config getOwnID]]) {
                //自己个人中心
                [Config saveOwnNicename:minstr([infoDic valueForKey:@"user_nickname"])];
                [Config saveUserSex:minstr([infoDic valueForKey:@"sex"])];
                [Config saveUserAvatar:minstr([infoDic valueForKey:@"avatar"])];
                [Config saveUserCity:minstr([infoDic valueForKey:@"city"])];
                [Config saveUserHomeTown:minstr([infoDic valueForKey:@"hometown"])];
            }
            self.titleL.text = minstr([infoDic valueForKey:@"user_nickname"]);
            _topView.dataDic = infoDic;
            [self updateTop:infoDic];
        }else if (code == 700){
            [PublicObj tokenExpired:msg];
        }else{
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        
    }];
}

-(void)updateTop:(NSDictionary *)infoDic {
    _like_switch = [strFormat([infoDic valueForKey:@"like_switch"]) intValue];
    _collect_switch = [strFormat([infoDic valueForKey:@"collect_switch"]) intValue];
    NSString *itemNums1 = [NSString stringWithFormat:@"%@ %@",YZMsg(@"作品"),[infoDic valueForKey:@"workVideos"]];
    NSDictionary *itemDic1 = @{@"tit":itemNums1,@"event":@"1"};
    NSString *itemNums2 = [NSString stringWithFormat:@"%@ %@",YZMsg(@"喜欢"),[infoDic valueForKey:@"likeVideos"]];
    NSDictionary *itemDic2 = @{@"tit":itemNums2,@"event":@"2"};
    NSString *itemNums3 = [NSString stringWithFormat:@"%@ %@",YZMsg(@"收藏"),[infoDic valueForKey:@"collectionVideos"]];
    NSDictionary *itemDic3 = @{@"tit":itemNums3,@"event":@"3"};
    /*
     if ([_otherUid isEqual:[Config getOwnID]]) {
         _dataArray = @[itemNums1,itemNums2,itemNums3];
     }else{
         _dataArray = @[itemNums1,itemNums2];
     }
     */
    _is_shop = [strFormat([infoDic valueForKey:@"isshop"]) intValue];
    
    NSMutableArray *m_array = [NSMutableArray array];
    [m_array addObject:itemDic1];
    if (_is_shop == 1) {
        NSString *itemShop = [NSString stringWithFormat:@"%@ %@",YZMsg(@"橱窗"),[infoDic valueForKey:@"shopGoods"]];
        NSDictionary *itemDic4 = @{@"tit":itemShop,@"event":@"4"};
        [m_array addObject:itemDic4];
    }
    if ([_otherUid isEqual:[Config getOwnID]]) {
        [m_array addObject:itemDic2];
        [m_array addObject:itemDic3];
    }else{
        if (_like_switch == 1) {
            [m_array addObject:itemDic2];
        }
        if (_collect_switch == 1) {
            [m_array addObject:itemDic3];
        }
    }
    _dataArray = [NSArray arrayWithArray:m_array];
    [_tabBar reloadData];
    [_pagerController reloadData];
}

-(void)topViewEvent:(TopCtrType)ctrType andRes:(NSDictionary *)resDic {
    if (ctrType == TopCtrType_Layout) {
        CGFloat top_height = [minstr([resDic valueForKey:@"top_height"]) floatValue];
        _topView.height = top_height;
        segStartY = _topView.height;
        if (!_isTabbar) {
            scrContentH = _window_height + segStartY-64-statusbarHeight;
        }else{
            scrContentH = _window_height + segStartY-49-64-statusbarHeight-ShowDiff;
        }
        _scrollview.contentSize = CGSizeMake(0, scrContentH);
        _tabBar.frame = CGRectMake(0, _topView.bottom, _window_width, 44);
        _pagerController.view.frame = CGRectMake(0, _tabBar.bottom, _window_width, scrContentH-segStartY-_tabBar.height);
    }else if (ctrType == TopCtrType_Attent){
        NSString *isattent = minstr([resDic valueForKey:@"isattent"]);
        if (self.followEvent) {
            self.followEvent(isattent);
        }
    }
}
#pragma mark - set/get
-(UIScrollView *)scrollview {
    if (!_scrollview) {
        CGFloat scrH = _window_height-49-ShowDiff;
        if (!_isTabbar) {
            scrH = _window_height;
        }
        _scrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0,_window_width, scrH)];
        _scrollview.backgroundColor = UIColor.whiteColor;
        _scrollview.delegate = self;
        _scrollview.bounces = NO;
        _scrollview.pagingEnabled = NO;
        _scrollview.showsVerticalScrollIndicator = NO;
        YBWeakSelf;
        _topView = [[YBCenterTopView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 0)];
        _topView.isChatPage = _isChatPage;
        _topView.isTabbar = _isTabbar;
        _topView.otherUid = _otherUid ? _otherUid : [Config getOwnID];;
        _topView.topEvent = ^(TopCtrType ctrType, NSDictionary *resDic) {
            [weakSelf topViewEvent:ctrType andRes:resDic];
        };
        [_scrollview addSubview:_topView];
        
//        _dataArray = @[YZMsg(@"作品"),YZMsg(@"喜欢"),YZMsg(@"收藏")];
        _dataArray = @[@{@"tit":YZMsg(@"作品"),@"event":@"1"},@{@"tit":YZMsg(@"喜欢"),@"event":@"2"},@{@"tit":YZMsg(@"收藏"),@"event":@"3"}];
        CGFloat cellSpace = 40;
        /*
        if (![_otherUid isEqual:[Config getOwnID]]) {
            _dataArray = @[YZMsg(@"作品"),YZMsg(@"喜欢")];
            cellSpace = 80;
        }
        */
        
        TYTabPagerBar *tabBar = [[TYTabPagerBar alloc]init];
        tabBar.dataSource = self;
        tabBar.delegate = self;
        tabBar.layout.barStyle = TYPagerBarStyleProgressView;
        tabBar.layout.selectedTextColor = UIColor.blackColor;
        tabBar.layout.normalTextColor = UIColor.grayColor;
        tabBar.layout.selectedTextFont = [UIFont boldSystemFontOfSize:17];
        tabBar.layout.normalTextFont = [UIFont systemFontOfSize:17];
        tabBar.layout.progressColor = UIColor.blackColor;
        tabBar.layout.progressHeight = 4;
        tabBar.layout.progressRadius = 2;
        tabBar.layout.progressHorEdging = 10;
        tabBar.layout.progressVerEdging = 5;
        tabBar.layout.cellWidth = 0;
        tabBar.layout.cellSpacing = cellSpace;
        tabBar.layout.adjustContentCellsCenter = YES;
        tabBar.backgroundColor = UIColor.clearColor;
        
        [tabBar registerClass:[TYTabPagerBarCell class] forCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier]];
        [_scrollview addSubview:tabBar];
        _tabBar = tabBar;
        TYPagerController *pagerController = [[TYPagerController alloc] init];
        pagerController.dataSource = self;
        pagerController.delegate = self;
        pagerController.layout.adjustScrollViewInset = NO;
        pagerController.layout.scrollView.backgroundColor = UIColor.whiteColor;
        [self addChildViewController:pagerController];
        [_scrollview addSubview:pagerController.view];
        _pagerController = pagerController;
        
    }
    return _scrollview;
}
#pragma mark - TYTabPagerBarDataSource
- (NSInteger)numberOfItemsInPagerTabBar {
    return _dataArray.count;
}
- (UICollectionViewCell<TYTabPagerBarCellProtocol> *)pagerTabBar:(TYTabPagerBar *)pagerTabBar cellForItemAtIndex:(NSInteger)index {
    UICollectionViewCell<TYTabPagerBarCellProtocol> *cell = [pagerTabBar dequeueReusableCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier] forIndex:index];
    NSDictionary *subDic = _dataArray[index];
    cell.titleLabel.text = strFormat([subDic valueForKey:@"tit"]);
    for (UIView *cellSub in cell.contentView.subviews) {
        if ([cellSub isKindOfClass:[UIImageView class]]) {
            [cellSub removeFromSuperview];
        }
    }

    int likeIdx = 1;
    int collectionIdx = 2;
    if (_is_shop == 1) {
        likeIdx = 2;
        collectionIdx = 3;
    }
    
    if ( [_otherUid isEqual:[Config getOwnID]] && ((index == likeIdx && _like_switch == 0) || (index == collectionIdx && _collect_switch == 0))) {
        UIImageView *imgeVV = [[UIImageView alloc]init];
        imgeVV.image = [UIImage imageNamed:@"wyt_lock"];
        [cell.contentView addSubview:imgeVV];
        [imgeVV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(15);
            make.centerY.equalTo(cell.contentView.mas_centerY);
            make.left.equalTo(cell.contentView.mas_right);
        }];
    }
    return cell;
}

#pragma mark - TYTabPagerBarDelegate
- (CGFloat)pagerTabBar:(TYTabPagerBar *)pagerTabBar widthForItemAtIndex:(NSInteger)index {
    NSDictionary *subDic = _dataArray[index];
    NSString *title = strFormat([subDic valueForKey:@"tit"]);
    return [pagerTabBar cellWidthForTitle:title];
}

- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar didSelectItemAtIndex:(NSInteger)index {
    [_pagerController scrollToControllerAtIndex:index animate:YES];
}

#pragma mark - TYPagerControllerDataSource
- (NSInteger)numberOfControllersInPagerController {
    return _dataArray.count;
}
- (UIViewController *)pagerController:(TYPagerController *)pagerController controllerForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
    /*
    int likeIdx = 1;
    int collectionIdx = 2;
    if (_is_shop == 1) {
        likeIdx = 2;
        collectionIdx = 3;
    }
    
    if (index == 0) {
        // 作品
        if (!_listVC1) {
            _listVC1 = [self createListVCType:ListType_Normal];
            YBWeakSelf;
            _listVC1.sawEvent = ^{
                [weakSelf scrollMainScorllViewToBot];
            };
        }
        _listVC1.foryouVideoId = _foryouVideoId ? _foryouVideoId:@"";
        return _listVC1;
    }else if (index == likeIdx){
        // 喜欢
        if (!_listVC2) {
            _listVC2 = [self createListVCType:ListType_Likes];
        }
        return _listVC2;
    }else if(index == collectionIdx){
        // 收藏
        if (!_listVC3) {
            _listVC3 = [self createListVCType:ListType_Collection];
        }
        return _listVC3;
    }else {
        // 橱窗
        if (!_shopListVC) {
            _shopListVC = [[WYTShopListVC alloc] init];
            _shopListVC.delegate = self;
            _shopListVC.otherUid = _otherUid ? _otherUid : [Config getOwnID];
            _shopListVC.isTabbar = _isTabbar;
        }
        return _shopListVC;
    }
    */
    
    NSDictionary *subDic = _dataArray[index];
    int eventIdx = [strFormat([subDic valueForKey:@"event"]) intValue];
    
    if (eventIdx == 1) {
        // 作品
        if (!_listVC1) {
            _listVC1 = [self createListVCType:ListType_Normal];
            YBWeakSelf;
            _listVC1.sawEvent = ^{
                [weakSelf scrollMainScorllViewToBot];
            };
        }
        _listVC1.foryouVideoId = _foryouVideoId ? _foryouVideoId:@"";
        return _listVC1;
    }else if (eventIdx == 2){
        // 喜欢
        if (!_listVC2) {
            _listVC2 = [self createListVCType:ListType_Likes];
        }
        return _listVC2;
    }else if(eventIdx == 3){
        // 收藏
        if (!_listVC3) {
            _listVC3 = [self createListVCType:ListType_Collection];
        }
        return _listVC3;
    }else {
        // 橱窗
        if (!_shopListVC) {
            _shopListVC = [[WYTShopListVC alloc] init];
            _shopListVC.delegate = self;
            _shopListVC.otherUid = _otherUid ? _otherUid : [Config getOwnID];
            _shopListVC.isTabbar = _isTabbar;
        }
        return _shopListVC;
    }
    
}
-(void)scrollMainScorllViewToBot {
    // _scrollview.contentOffset = CGPointMake(0, scrContentH-_window_height);
    [_scrollview setContentOffset:CGPointMake(0, scrContentH-_window_height) animated:YES];
}
-(CenterListVC *)createListVCType:(ListType)listType {
    CenterListVC *listVC = [[CenterListVC alloc]init];
    listVC.delegate = self;
    listVC.listType = listType;
    listVC.otherUid = _otherUid ? _otherUid : [Config getOwnID];
    listVC.isTabbar = _isTabbar;
    return listVC;
}
#pragma mark - TYPagerControllerDelegate
- (void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated {
    [_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex animate:animated];
}
-(void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress {
    [_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex progress:progress];
}
- (void)pagerController:(TYPagerController *)pagerController viewDidAppear:(UIViewController *)viewController forIndex:(NSInteger)index;{
    // 使用空数据代理会引起滑动问题,这里主动调用一下didScroll重置子视图的滚动属性
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self scrollViewDidScroll:_scrollview];
    });
}
#pragma mark - 设置滑动事件
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    //NSLog(@"centerVC======%f",velocity.y);
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"centerVC==scrContentH:%f===did-scr===%f",segStartY-64-statusbarHeight,scrollView.contentOffset.y);
    if(scrollView.contentOffset.y >= segStartY-64-statusbarHeight){
        _listVC1.collectionView.scrollEnabled = YES;
        _listVC2.collectionView.scrollEnabled = YES;
        _listVC3.collectionView.scrollEnabled = YES;
        [self.view bringSubviewToFront:self.naviView];
    }else{
        _listVC1.collectionView.scrollEnabled = NO;
        _listVC2.collectionView.scrollEnabled = NO;
        _listVC3.collectionView.scrollEnabled = NO;
        [self.view sendSubviewToBack:self.naviView];
    }
    
    self.titleL.alpha = scrollView.contentOffset.y/(segStartY-64-statusbarHeight);
    self.subNavi.alpha = scrollView.contentOffset.y/(segStartY-64-statusbarHeight);
}

-(void)listScrollToTop:(CGFloat)Y{
    if (Y <0) {
        [_scrollview setContentOffset:CGPointMake(0,0) animated:YES];
    }
}
@end
